package cn.datawin.util;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ThreadUtil {
	
	/*public static void singleExec(final ThreadRunable threadRunable, final long millis){
		ExecutorService  singleThread = Executors.newSingleThreadExecutor();
		
		singleThread.execute(new Runnable() {
			
			@Override
			public void run() {
				while(!threadRunable.stop()){
					try{
						threadRunable.exec();
						if(millis != 0L){
							Thread.sleep(millis);
						}
					}catch(Exception e){
						log.error("singleExec::", e);
						continue;
					}
				}
			}
		});
	}*/
	
	
	public static void singleExec(final ThreadRunable threadRunable, final long millis) {
		new Thread(new Runnable() {
			public Log log  = LogFactory.getLog(getClass()); 
			@Override
			public void run() {
				while (!threadRunable.stop()) {
					try {
						threadRunable.exec();
						if (millis != 0L) {
							Thread.sleep(millis);
						}
					} catch (Exception e) {
						e.printStackTrace();
						log.error("singleExec::", e);
						continue;
					}finally{
						log.info("continue::"+ !threadRunable.stop());
					}
				}
			}
		}).start();

	}
	
	public static void exec(Runnable runnable){
		new Thread(runnable).start();
	}
	
	/**
	static ThreadPoolExecutor threadPools = new ThreadPoolExecutor(5, 100, 1000000, TimeUnit.MILLISECONDS, 
			new LinkedBlockingQueue<Runnable>(3000), new ThreadPoolExecutor.CallerRunsPolicy());

	public static void exec_list(Runnable runnable){
		threadPools.execute(runnable);
	}**/
	
	public static abstract class ThreadRunable{
		public abstract void exec() throws Exception;
		public boolean stop(){
			return false;
		};
	}

}
